<?php
namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Form\Annotation\AnnotationBuilder;
use Zend\View\Model\ViewModel;
use Admin\Form\LoginForm;
use Admin\Model\AuthUser;

class AuthController extends AbstractActionController{

	public $view;
	protected $form;
	protected $storage;
	protected $authService;

	public function __construct(){
		$this->view = new ViewModel();
	}

	public function getAuthService(){
		if(!$this->authService){
			$this->authService = $this->getServiceLocator()->get('AuthService');
		}
		return $this->authService;
	}

	public function getSessionStorage(){
		if(!$this->storage){
			$this->storage = $this->getServiceLocator()->get('Admin\Model\MyAuthStorage');
		}

		return $this->storage;
	}

	public function getForm(){
		if(!$this->form){
			$this->form = new LoginForm();
		}
		return $this->form;
	}

	public function loginAction(){
		$this->layout('layout/login');
		if($this->getAuthService()->hasIdentity()){
			return $this->redirect()->toRoute(NULL,array('controller'=>'success','action'=>'index'));
		}
		
		$this->view->form = $this->getForm();
		$this->view->message = $this->flashMessenger()->getMessages();
		return $this->view;
	}

	public function authenticateAction(){
		// kiểm tra thông tin đăng nhập
		$this->layout('layout/admin');
		$form = $this->getForm();
		$redirect = array('controller'=>'auth','action'=>'login');

		$request = $this->getRequest();
		if($request->isPost()){
			$form->setData($request->getPost());
			if($form->isValid()){
				$this->getAuthService()->getAdapter()
										->setIdentity($request->getPost('username'))
										->setCredential($request->getPost('password'));
				$result = $this->getAuthService()->authenticate();
				foreach($result->getMessages() as $message){
					$this->flashMessenger()->addMessage($message);
				}

				if($result->isValid()){
					$redirect = array('controller'=>'index','action'=>'index');
					if($request->getPost('remember') == 1){
						$this->getSessionStorage()->setRememberMe(1);
						/* set storage again */
						$this->getAuthService()->setStorage($this->getSessionStorage());
					}

					$this->getAuthService()->getStorage()->write($request->getPost('username'));
				}
			}
		}

		return $this->redirect()->toRoute(NULL,$redirect);
	}

	public function logoutAction(){
		$this->layout('layout/admin');
		echo "logoutAction";
		$this->getSessionStorage()->forgetMe();
		$this->getAuthService()->clearIdentity();

		$this->flashMessenger()->addMessage("You've been logged out");
		return $this->redirect()->toRoute(NULL,array('controller'=>'auth','action'=>'login'));	
	}
}